package com.ruoyi.framework.interceptor;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.ruoyi.framework.web.exception.ServiceException;
import com.ruoyi.project.system.login.domain.MiniSysUser;
import com.ruoyi.project.system.login.service.IMiniSysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private IMiniSysUserService miniSysUserService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        if(StrUtil.isBlank(token)){
            throw new ServiceException(401,"无token,请重新登陆");
        }
        String loginName;
        try {
            loginName = JWT.decode(token).getAudience().get(0);
        } catch (JWTDecodeException j){
            throw new ServiceException(401,"token验证失败");
        }
        MiniSysUser miniSysUser = miniSysUserService.selectMiniSysUserByLoginName(loginName);
        if(miniSysUser == null){
            throw new ServiceException(401,"用户不存在,请重新登录");
        }
        //用户密码加签验证token
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(miniSysUser.getPassword())).build();
        try {
            jwtVerifier.verify(token);
        } catch (JWTVerificationException e){
            throw new ServiceException(401,"用户不存在,请重新登录");
        }
        return true;
    }
}
